/*
 * @Author: MuQuanyu(MQy)
 * @Date: 2025-09-04 13:55:40
 * @LastEditTime: 2025-10-16 10:06:07
 * @email: muquanyu@outlook.com
 */
import type { RouteRecordRaw } from "vue-router";
import NotFound from "@/views/Other/404.vue";
export function buildRoutesFromServer(
  serverRouteNodeList: ServerRouteNode[],
  parentFullPath = ""
): RouteRecordRaw[] {
  return serverRouteNodeList.map((node: ServerRouteNode) => {
    const currentFullPath = parentFullPath
      ? `${parentFullPath.replace(/\/$/, "")}/${node.path.replace(/^\//, "")}`
      : node.path; // 根节点直接使用 node.path
    const route: RouteRecordRaw = {
      path: node.path,
      name: node.name || undefined,
      redirect: node.extMeta?.redirect || undefined, // 如果有重定向，那就用上
      meta: {
        title: node.title || undefined,
        iconType: node.iconType || undefined,
        icon: node.icon || undefined,
        hidden: node.hidden || false,
        requireAuth: node.requireAuth ?? true, // 是否需要 token 认证
        keepAlive: node.keepAlive || false,
        type: node.type,
        external: node.external || false,
        externalUrl: node.externalUrl || undefined,
        parentId: node.parentId || undefined,
        fullPath: currentFullPath, // 新增：存储完整路径
        component: node.component,
        sort: node.sort,
        id: node.id,
        ...node.extMeta, // 额外的 meta
        // permissions: node.permissionList?.map(p => p.permission) || [], // 提取权限标识
      } as Record<string, any>,
    } as RouteRecordRaw;
    // 处理组件部分
    if (node.component) {
      if (node.external) {
        // 它是外链
        route.component = () => null;
      } else {
        route.component = node.component
          ? () =>
              import(`../../${node.component?.replace("@/", "")}`)
                .then((m) => m.default || m)
                .catch(() => NotFound) // 兜底
          : NotFound; // 我的后端是返回的 @/views/Dashboard/Analysis/index.vue
      }
    }
    // ========= 个人认为应该给目录弄个重定向处理 =========
    if (node.type === 0 && node.children?.length) {
      // 递归查找第一个可见的非目录子节点（type !== 0）
      const findFirstValidChild = (
        children: ServerRouteNode[],
        parentPath: string // 当前目录节点的完整路径（如 '/dashboard'）
      ): string | null => {
        for (const child of children) {
          if (child.hidden) continue; // 跳过隐藏节点

          if (child.type !== 0) {
            // 找到页面节点（非目录）
            // 拼接父路径和子路径：parentPath + '/' + child.path（处理斜杠）
            return `${parentPath.replace(/\/$/, "")}/${child.path.replace(/^\//, "")}`;
          } else if (child.children?.length) {
            // 子节点是目录，递归查找
            const grandChildPath = findFirstValidChild(
              child.children,
              `${parentPath.replace(/\/$/, "")}/${child.path.replace(/^\//, "")}` // 子目录的完整路径
            );
            if (grandChildPath) return grandChildPath;
          }
        }
        return null; // 没有找到有效子节点
      };

      // 生成重定向路径（基于当前目录的完整路径 parentFullPath）
      const redirectPath = findFirstValidChild(node.children, currentFullPath);
      if (redirectPath) {
        route.redirect = redirectPath; // 如：/dashboard/analysis
      }
    }

    // ========= 上方为重定向处理 =========
    // 下方为递处理子路由
    if (node.children?.length) {
      route.children = buildRoutesFromServer(node.children, currentFullPath);
    }
    return route;
  }) as any;
}

export function extractKeepAliveList(routes: RouteRecordRaw[], parentFullPath = ""): string[] {
  const keepAliveList: string[] = [];

  function traverse(routes: RouteRecordRaw[]) {
    routes.forEach((route) => {
      // 如果当前路由需要缓存且有名称为 name，则加入列表
      if (route.meta?.keepAlive && route.name) {
        keepAliveList.push(route.name as string);
      }
      // 递归处理子路由
      if (route.children) {
        traverse(route.children);
      }
    });
  }

  traverse(routes);
  return keepAliveList;
}
